package com.github.cyf.controller;

import com.github.cyf.common.module.Rs;
import com.github.cyf.util.MinioUtil;
import com.github.cyf.domain.po.SysOss;
import com.github.cyf.domain.vo.SysOssUploadVo;
import com.github.cyf.service.SysOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenyifan
 * @create 2024-03-16 14:02
 */
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
@Api(tags = "文件服务")
public class SysOssController {

    private final SysOssService sysOssService;
    private final MinioUtil minioUtil;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation("上传文件")
    public Rs upload(@RequestPart("file") MultipartFile file) {
        if (file == null) {
            return Rs.error("上传文件不能为空");
        }
        SysOss sysOss = sysOssService.upload(file);
        SysOssUploadVo uploadVo = new SysOssUploadVo();
        uploadVo.setUrl(sysOss.getUrl());
        uploadVo.setFileName(sysOss.getOriginalName());
        uploadVo.setOssId(sysOss.getOssId().toString());
        return Rs.ok("上传成功").setData(uploadVo);
    }

    @PostMapping("/download")
    @ApiOperation("下载文件")
    public Rs download(String object, HttpServletResponse response) {
        minioUtil.download(object, response);
        return Rs.ok("下载成功");
    }

    @PostMapping("/createBucket")
    @ApiOperation("创建bucket")
    public Rs createBucket(String bucketName) {
        minioUtil.createBucket(bucketName);
        return Rs.ok("创建bucket成功");
    }

    @PostMapping("/removeBucket")
    @ApiOperation("删除bucket")
    public Rs removeBucket(String bucketName) {
        minioUtil.removeBucket(bucketName);
        return Rs.ok("删除bucket成功");
    }

    @GetMapping("/existBucket")
    @ApiOperation("判断bucket是否存在")
    public Rs existBucket(String bucketName) {
        boolean exist = minioUtil.existBucket(bucketName);
        return exist ? Rs.ok("bucket存在") : Rs.ok("bucket不存在");
    }

    @PostMapping("/removeObject")
    @ApiOperation("删除文件对象")
    public Rs removeObject(String object) {
        minioUtil.removeObject(object);
        return Rs.ok("删除成功");
    }

    @GetMapping("preview")
    @ApiOperation("预览图片")
    public Rs preview(String object) {
        String url = minioUtil.preview(object);
        return Rs.ok("获取成功").setData(url);
    }

}
